package com.jf3q.sup.controller;

import com.jf3q.sup.domain.Users;
import com.jf3q.sup.dto.LoginDto;
import com.jf3q.sup.service.UsersService;
import com.jf3q.sup.utils.JwtUtils;
import com.jf3q.sup.vo.LoginVo;
import com.jf3q.sup.vo.PersonalVo;
import com.jf3q.sup.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
@CrossOrigin
public class UserController {
    @Autowired
    UsersService usersService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginDto loginDto) {
        Users user = (Users) usersService.loadUserByUsername(loginDto.getUsername());
        if (!passwordEncoder.matches(loginDto.getPassword(), user.getPassword())) {
            return ResultVo.error("账号或密码不正确!!!");
        }
        if(user.getStatus()==0){
            return ResultVo.error("账号已被禁用，无法登录！");
        }
        String token = JwtUtils.getToken(user.getUsername());
        //将用户的凭证存入到security的上下文中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setUsername(user.getUsername());
        return ResultVo.success("登录成功!!!", loginVo);
    }

    /**
     * 查看个人中心
     *
     * @return
     */
    @GetMapping
    public ResultVo getPersonal() {
        PersonalVo personalVo = null;
        try {
            personalVo = usersService.selectPersonalVo();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return ResultVo.success("", personalVo);
    }

    /**
     * 修改个人中心
     *
     * @return
     */
    @PutMapping
    public ResultVo updatePersonal(@RequestBody PersonalVo personalVo) {
        try {
            usersService.updatePersonal(personalVo, passwordEncoder);
            return ResultVo.success("修改成功!!!", null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
